package com.djk.interceptor;

import com.djk.constants.SessionKeys;
import com.djk.pojo.User;
import com.djk.utils.IdUtil;
import com.djk.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(SessionKeys.USER_INFO_SESSION);
        //未登录,拦截
        if (user == null) {
            response.setStatus(401);
            return false;
        }
        IdUtil.setId(user.getId());
        log.info("用户登录成功！");
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        IdUtil.remove();
    }

}
